package com.weixin.thread;

import lombok.SneakyThrows;

import java.util.concurrent.locks.Lock;

/**
 * @ClassName Window
 * @Description
 * @date 2022/2/22 16:07
 * @author: wx
 * @Version 1.0
 */
public class Window extends Thread {

    private static int ticket = 5;

    @Override
    public void run() {
        show();
    }

    private void show() {
        while (true) {
            if (ticket > 0) {
                System.out.println(getName() + "卖票,票号为" + ticket);
                ticket--;
            } else {
                break;
            }
        }
    }
}

class Windows implements Runnable {

    private int tickets = 5;
    final String s = "lock";

    @SneakyThrows
    @Override
    public void run() {
        while (true) {
            //使用锁，任何一个对象都可以充当锁
            synchronized (s) {
                if (tickets > 0) {
                    System.out.println(Thread.currentThread().getName() + "卖票,票号为" + tickets);
                    tickets--;
                } else {
                    break;
                }
            }
        }
    }
}

class runMain {
    public static void main(String[] args) {
        Windows windows = new Windows();

        Thread t1 = new Thread(windows);
        Thread t2 = new Thread(windows);
        Thread t3 = new Thread(windows);

        t1.start();
        t2.start();
        t3.start();
    }
}

